import requests,re


def get_gitee_raw_file(owner, repo, branch, file_path, access_token=None):
    """
    获取 Gitee 仓库中某个文件的 raw 内容
    :param owner: 仓库所有者
    :param repo: 仓库名称
    :param branch: 分支名称
    :param file_path: 文件路径
    :param access_token: 可选，Gitee 访问令牌
    :return: 文件内容
    """
    base_url = "https://gitee.com/api/v5/repos"
    url = f"{base_url}/{owner}/{repo}/contents/{file_path}?ref={branch}"

    headers = {
        "Accept": "application/json"
    }

    if access_token:
        headers["Authorization"] = f"Bearer {access_token}"

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        file_info = response.json()
        if file_info != []:
            download_url = file_info["download_url"]
            raw_content = requests.get(download_url).text
            return raw_content
        else:
            print('远程仓库无one_key_template.py')
            return ''
    else:
        raise Exception(f"Failed to fetch file: {response.status_code}, {response.text}")

def check_version(local_version):
    owner = "fang-yuantong"
    repo = "one_key"
    branch = "master"
    file_path = "one_key_template.py"

    # 如果是私有仓库，请提供 access token
    access_token = None

    content = get_gitee_raw_file(owner, repo, branch, file_path, access_token)
    # print(content)
    if content != '':
        remote_version = re.findall('one_key_version = \'(\S+)\'', content)[0]
        remote_version = int(remote_version)
        local_version = int(get_local_version())
        if local_version < remote_version:
            print('本地版本号小于远程仓库,正在更新one_key_template')
            with open('one_key_template.py', 'w', encoding='utf-8') as f:
                f.write(content)
        elif  local_version > remote_version:
            print('版本号大于远程仓库,无需更新本地one_key_template,需更新远程one_key_template仓库')
            input('todo')
            # todo
            # exit()
        else:
            print('版本号一致，无需更新')
    else:
        print('远程仓库无one_key_template.py,视为本地版本大于远程版本,需更新远程one_key_template仓库')
        input('tod')
        # todo

def get_local_version():
    with open('one_key_template.py','r',encoding='utf-8') as f:
        content = f.read()
        local_version = re.findall('one_key_version = \'(\S+)\'', content)[0]
    return local_version

def create_one_key_template():
    owner = "fang-yuantong"
    repo = "one_key"
    branch = "master"
    file_path = "one_key.py"

    # 如果是私有仓库，请提供 access token
    access_token = None
    content = get_gitee_raw_file(owner, repo, branch, file_path, access_token)
    with open('one_key_template.py', 'w', encoding='utf-8') as f:
        f.write(content)


# 使用示例
if __name__ == "__main__":
    one_key_version = '052701'
    check_version(one_key_version)
